<?php

namespace App\Admin\Extensions\Tools;

use Dcat\Admin\Admin;
use Dcat\Admin\Grid\Tools\AbstractTool;

class ImportButton extends AbstractTool
{
    protected $uploadRoute;

    protected $jsCallBack;

    /**
     * ImportButton constructor.
     * @param null $title
     * @param string $uploadRoute 处理文件api
     * @param string $jsCallBack 处理js回调
     */
    public function __construct($title = null, $uploadRoute = '', $jsCallBack = '')
    {
        parent::__construct($title);
        $this->uploadRoute = $uploadRoute;
        $this->jsCallBack = $jsCallBack;
    }

    public function render()
    {
        Admin::script($this->script());

        return view('admin.tools.import_button', [
            'title' => $this->title,
        ]);
    }

    protected function script()
    {
        return <<<JS
            $(".custom-btn-input").on('change', function(e) {
                let fromData = new FormData();
                fromData.append('file', $(this)[0].files[0]);
                $.ajax({
                    url: "$this->uploadRoute",
                    data: fromData,
                    type: 'POST',
                    contentType: false,
                    processData: false,
                    success: function (s) {
                    console.log(s)
                    Dcat.success(s.message)
                    // 开启loading效果
                    Dcat.loading();

                    // 3秒后自动移除loading效果
                    setTimeout(function () {
                        Dcat.loading(false);
                        Dcat.reload();
                    },5000)
                        // if ("$this->jsCallBack") {
                        //     eval("$this->jsCallBack");
                        // }
                    },
                    error: function(e) {
                        console.error(e.responseJSON.message);
                        Dcat.error(e.responseJSON.message);
                    }
                });
            });

            $(".custom-btn").on('click', function() {
                $(".custom-btn-input").click();
            });
JS;
    }
}
